local desc_lm_mode = [[
  # 鹿鸣简介
  ___

  规则：

  【玩法】

    该模式所有玩家扮演的是“主公”角色，即有体力的、拥有发现将领能力的角色。

    每个主公角色都有其所属势力的将领池，且主公角色拥有所有获得的将领的技能。

  【胜利条件】

    活到最后的人胜利。

  【牌堆】

  本模式将军争牌堆的乐不思蜀、兵粮寸断分别替换成了趁火打劫、随机应变，

  五谷丰登也改成了鹿鸣版本。

  【名词】

    - 军力技：定义初始将领上限的技能，有军力技的角色即为“主公”，
    军力技一般在游戏开始时触发，用以初始化将领牌堆和获得初始将领。
    在鹿鸣模式中，玩家只能使用有军力技的武将（即上文所述之“主公角色”）。

    - 将领：没有体力值的角色，拥有此将领的主公拥有其所有技能。

    - 发现：观看将领池顶三张将领牌，三选一获得一名将领，然后将剩余的将领牌洗回将领池。

    - 移除：将一名登场的将领洗回将领池，
    特别的，被“移出游戏”的将领不会洗回将领池。

  【霸主】

    游戏开始时，随机一名玩家成为主公（身份），称为“霸主”。
  
    霸主效果（X为其他角色数-1）：
      1.获得此身份后，加X点体力上限，回复X点体力。
      2.摸牌阶段多摸X张牌。
      ※以下三项仅存活人数多于2时生效※
      3.使用【杀】的次数上限+1。
      4.视为拥有三国杀的“标·刚烈”。
      5.跳过判定阶段。

    霸主死亡时，伤害来源如果存活，其成为霸主，否则原霸主的下家成为霸主。

    若仅剩一人存活，其成为霸主并胜利。
]]

local U = require "packages/utility/utility"
local LM = require "packages/luming/LM"

local lm_mode_test = false  --开启测试可以自由选将
local whilecards = {"standard","standard_cards","maneuvering","luming_cards"} --白名单卡组

local LM_getLogic = function()
  local LM_logic = GameLogic:subclass("LM_logic")
  -- function LM_logic:initialize(room)
  --   GameLogic.initialize(self, room)
  --   self.role_table = {
  --     { "renegade" },
  --     { "renegade", "renegade" },
  --     { "renegade", "renegade", "renegade" },
  --     { "renegade", "renegade", "renegade", "renegade" },
  --     { "renegade", "renegade", "renegade", "renegade", "renegade" },
  --     { "renegade", "renegade", "renegade", "renegade", "renegade", "renegade" },
  --     { "renegade", "renegade", "renegade", "renegade", "renegade", "renegade", "renegade" },
  --     { "renegade", "renegade", "renegade", "renegade", "renegade", "renegade", "renegade", "renegade" },
  --   }
  -- end

  -- function LM_logic:prepareDrawPile()
  --   local room = self.room
  --   local seed = math.random(2 << 32 - 1)
  --   --重新过滤卡组
  --   local filterCardIds = {}
  --   local allCardIds = {}
  --   for _, card in ipairs(Fk.cards) do
  --     if card.package.name == "luming_cards" or not table.contains(room.disabled_packs, card.package.name) then
  --       table.insert(allCardIds, card.id)
  --     end
  --   end
  --   local replaces = {"indulgence", "supply_shortage", "amazing_grace"}
  --   for i = 1, #allCardIds do
  --     local id = allCardIds[i]
  --     local card = Fk:getCardById(id)
  --     if card then
  --       if card.is_derived then
  --         table.insert(room.void, id)
  --         room:setCardArea(id, Card.Void, nil)
  --       else
  --         -- if table.contains(whilecards,card.package.name) then
  --         if not table.contains(replaces,card.name) then
  --           table.insert(filterCardIds,id)
  --         end
  --         -- end
  --       end
  --     end
  --   end
  --   table.shuffle(filterCardIds, seed)
  --   room.draw_pile = filterCardIds
  --   for _, id in ipairs(room.draw_pile) do
  --     room:setCardArea(id, Card.DrawPile, nil)
  --   end

  --   room:doBroadcastNotify("PrepareDrawPile", seed)
  -- end

  function LM_logic:assignRoles()
    local room = self.room
    local hasrole = true
    room:setBanner("@[:]mode_desc", "lm_mode_desc")
    for _,p in ipairs(room.players) do
      if hasrole and p.id > 0 then
        p.role = "lord"
        hasrole = false
      else
        p.role = "renegade"
      end
    end
  end

  function LM_logic:chooseGenerals()
    local room = self.room ---@class Room
    local generalNum = room.settings.generalNum
    local lord = room:getLord()
    room:setCurrent(lord)
    local whilegens = table.simpleClone(room.general_pile)-- {"lm__caocao","lm__lord_dongzhuo", "lm__liuhong","lm__lord_liubei"}
    -- local whilegens = {"lm__lord_liubei"}
    -- table.shuffle(whilegens)

    local players = room.players
    local req = Request:new(players, "AskForGeneral")
    local i = 1
    local s = #whilegens // #players
    for _, pr in ipairs(room.players) do
      if pr.id > 0 then
        local selgens = {}
        if i < #whilegens and s > 0 then
          selgens = table.slice(whilegens, i, i + s)
          i = i + s
        else
          selgens = table.random(selgens, math.max(s, 1))
        end
        -- table.insert(selgens, "blank_shibing")
        req:setData(pr, { selgens, 1 })
        req:setDefaultReply(pr, table.random(selgens, 1))
      else
        req:setData(pr, { {"lm__caopi"}, 1 })
        req:setDefaultReply(pr, {"lm__caopi"})
      end
      -- p.request_data = json.encode({
      --   path = "packages/luming/qml/LM_ChooseGeneralBox.qml",
      --   data = p.id > 0 and {whilegens} or {{"blank_shibing"}}
      -- })
      -- p.default_reply = "blank_shibing"
    end

    req:ask()
    local selected = {}
    for _, pr in ipairs(room.players) do
      local g = req:getResult(pr)[1]
      table.insert(selected, g)
      room:setPlayerGeneral(pr, g, true, true)
    end
    room.general_pile = table.filter(room.general_pile, function(g) return not table.contains(selected, g) end)

    room:askForChooseKingdom(room.players)
    for _, p in ipairs(room.players) do
      room:setPlayerProperty(p, "role_shown", true)
      room:setPlayerProperty(p, "role", "hidden")
    end
  end
  return LM_logic
end

local lm_baqi = fk.CreateTriggerSkill{
  name = "lm_baqi",
  anim_type = "masochism",
  events = {fk.Damaged},
  on_use = function(self, event, target, player, data)
    local room = player.room
    local from = data.from
    if from and not from.dead then room:doIndicate(player.id, {from.id}) end
    local judge = {
      who = player,
      reason = self.name,
      pattern = ".|.|^heart",
    }
    room:judge(judge)
    if judge.card.suit ~= Card.Heart and from and not from.dead then
      local discards = room:askForDiscard(from, 2, 2, false, self.name, true)
      if #discards == 0 then
        room:damage{
          from = player,
          to = from,
          damage = 1,
          skillName = self.name,
        }
      end
    end
  end,
}
Fk:addSkill(lm_baqi)

local beComeKing = function(player)
  local room = player.room
  -- room:setPlayerMark(player,"@@lm_king",1)
  local otherplayers = room:getOtherPlayers(player)
  local value = #otherplayers - 1
  if value > 0 then
    player.hp = player.hp + value
    player.maxHp = player.maxHp + value
    room:setPlayerProperty(player, "hp", player.hp)
    room:setPlayerProperty(player, "maxHp", player.maxHp)
  end
  if #room.alive_players > 2 then
    room:handleAddLoseSkills(player, "lm_baqi", nil, true, false)
  else
    if player:hasSkill("lm_baqi") then
      room:handleAddLoseSkills(player, "-lm_baqi", nil, true, false)
    end
  end
end

local slashadd_mode = fk.CreateTargetModSkill{
  name = "#slashadd_mode",
  residue_func = function(self, player, skill, scope)
    if player:hasSkill(self) and skill.trueName == "slash_skill"
      and player.role == "lord" and #Fk:currentRoom().alive_players > 2 then
      return 1
    end
  end,
}
Fk:addSkill(slashadd_mode)

--鹿鸣模式
local LM_rule = fk.CreateTriggerSkill{
  name = "#LM_rule",
  priority = 0.00001,
  events = {fk.GameStart,fk.EventPhaseChanging,fk.BuryVictim,fk.DrawNCards,fk.GameOverJudge},
  can_trigger = function(self, event, target, player, data)
    if event == fk.GameStart then
      return player == target
    elseif event == fk.EventPhaseChanging then
      return player == target and data.to == Player.Judge and player.role == "lord" and #player.room.alive_players > 2
    elseif event == fk.BuryVictim then
      return player == target
    elseif event == fk.GameOverJudge then
      return player == target
    elseif event == fk.DrawNCards then
      return player == target and player.role == "lord"
    end
  end,
  on_trigger = function(self, event, target, player, data)
    local room = player.room
    if event == fk.GameStart then
      -- room:setTag("SkipGameRule", true)
      room:setTag("SkipNormalDeathProcess", true)
      local lord = table.random(room.alive_players)
      if lord:isAlive() then
        room:setPlayerProperty(lord, "role", "lord")
        room:handleAddLoseSkills(lord, "#slashadd_mode", nil, false, false)
        beComeKing(lord)
      end
    elseif event == fk.EventPhaseChanging then
      player:skip(data.to)
      return true
    elseif event == fk.DrawNCards then
      local otherplayers = room:getOtherPlayers(player)
      local value = #otherplayers - 1
      if value > 0 then
        data.n = data.n + value
      end
    elseif event == fk.BuryVictim then
      if target.role == "lord" then
        room:setPlayerProperty(target, "role", "hidden")
        if target and target:hasSkill("lm_baqi") then
          room:handleAddLoseSkills(target, "-lm_baqi", nil, true, false)
        end
        local newlord = target:getNextAlive()
        local killer = data.damage and data.damage.from or nil ---@type ServerPlayer?
        if killer and killer:isAlive() then newlord = killer end
        room:setPlayerProperty(newlord, "role", "lord")
        beComeKing(newlord)
      end
      if #room.alive_players <= 2 then
        local lord = table.find(room.alive_players, function(p) return p.role == "lord" end)
        if lord and lord:hasSkill("lm_baqi") then
          room:handleAddLoseSkills(lord, "-lm_baqi", nil, true, false)
        end
      end
    elseif event == fk.GameOverJudge then
      if #room.alive_players == 1 then
        for _, p in ipairs(room.players) do
          room:setPlayerProperty(p, "role", "hidden")
        end
        room:setPlayerProperty(room.alive_players[1], "role", "lord")
        room:gameOver("lord")
      end
      -- room:setTag("SkipGameRule", true)
    end
  end,
}
Fk:addSkill(LM_rule)
local lm_mode = fk.CreateGameMode{
  name = "lm_mode",
  minPlayer = 2,
  maxPlayer = 8,
  rule = LM_rule,
  logic = LM_getLogic,
  winner_getter = function(self, victim)
    if not victim.surrendered and victim.rest > 0 then
      return ""
    end
    local room = victim.room
    local alive = table.filter(room.players, function(p) ---@type Player[]
      return not p.surrendered and not (p.dead and p.rest == 0)
    end)
    if #alive > 1 then return "" end
    return "lord"
  end,
  whitelist = function(self, pkg)
    local standard = {"standard_cards", "maneuvering"}
    if table.contains(standard, pkg.name) then return true end
    return pkg.game_modes_whitelist and table.contains(pkg.game_modes_whitelist, self.name)
  end,
  surrender_func = function(self, playedTime)
    local surrenderJudge = { { text = "time limitation: 10s", passed = playedTime >= 10 } }
    table.insert(surrenderJudge, { text = "only you alive", passed = #Fk:currentRoom().alive_players <= 2 })
    -- if Self.role ~= "lord" then
    -- end
    return surrenderJudge
  end,
  build_draw_pile = function(self)
    local draw_pile, void = GameMode.buildDrawPile(self)
    local room = Fk:currentRoom()
    --重新过滤卡组
    local replaces = {"indulgence", "supply_shortage", "amazing_grace"}
    for i = #draw_pile, 1, -1 do
      local id = draw_pile[i]
      local card = Fk:getCardById(id)
      if card then
        if table.contains({"standard_cards", "maneuvering"}, card.package.name) and table.contains(replaces, card.name) then
          table.remove(draw_pile, i)
        end
      end
    end
    return draw_pile, void
  end
}

Fk:loadTranslationTable{
  ["lm_mode"] = "鹿鸣模式",
  ["LM_rule"] = "鹿鸣模式",

  ["@@lm_king"] = "霸主",
  ["lm_baqi"] = "霸气",
  [":lm_baqi"] = "当你受到伤害后，你可以进行判定：若结果不为<font color='red'>♥</font>，则伤害来源选择一项：弃置两张手牌，或受到1点伤害。",

  ["#lm_removeservants"] = "移除将领",
  ["#lm_findservants"] = "发现将领",
  ["#lm_checkservants"] = "检索将领",
  ["@lm_svtsinfo"] = "将领:",

  ["time limitation: 10s"] = "游戏时长达到10秒",
  ["only you alive"] = "仅剩两人存活",

  [":lm_mode"] = desc_lm_mode,
  ["lm_mode_desc"] = "鹿鸣",
  [":lm_mode_desc"] = [[<br>
1.把其他人全杀了就赢了。<br>
2.霸主有刚烈和英姿双刀（人越多英姿摸越多），进单挑就没了。<br>
3.杀了霸主能成为霸主。<br>
4.发现将领能获得将领的技能。
]],
}

return lm_mode
